package com.smart.campus.web.controller.school;

import java.io.*;
import java.util.ArrayList;
import java.util.List;

import com.smart.campus.common.config.Global;
import com.alibaba.fastjson.JSONObject;
import com.smart.campus.common.utils.DateUtils;
import com.smart.campus.framework.util.ShiroUtils;
import com.smart.campus.school.domain.ExamRoomClasses;
import com.smart.campus.school.domain.ExamRoomStudents;
import com.smart.campus.school.domain.Grade;
import com.smart.campus.school.service.IExamRoomClassesService;
import com.smart.campus.school.service.IExamRoomStudentsService;
import com.smart.campus.school.service.IGradeService;
import com.smart.campus.system.domain.SysUser;
import com.smart.campus.web.utils.PdfUtil;
import com.smart.campus.web.utils.SchoolUtil;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.io.IOUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.smart.campus.common.annotation.Log;
import com.smart.campus.common.enums.BusinessType;
import com.smart.campus.school.domain.ExamRoomSchedule;
import com.smart.campus.school.service.IExamRoomScheduleService;
import com.smart.campus.common.core.controller.BaseController;
import com.smart.campus.common.core.domain.AjaxResult;
import com.smart.campus.common.utils.poi.ExcelUtil;
import com.smart.campus.common.core.page.TableDataInfo;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import static com.smart.campus.web.utils.PdfUtil.createPdf;

/**
 * 考场安排Controller
 * 
 * @author Zhihe.Li
 * @date 2020-06-03
 */
@Controller("examSchedule")
@RequestMapping("/school/examSchedule")
public class ExamRoomScheduleController extends BaseController
{
    private String prefix = "school/examSchedule";

    @Autowired
    private IExamRoomScheduleService examRoomScheduleService;

    @Autowired
    private IExamRoomClassesService examRoomClassesService;

    @Autowired
    private IExamRoomStudentsService examRoomStudentsService;
    @Autowired
    private IGradeService gradeService;

    @RequiresPermissions("school:examSchedule:view")
    @GetMapping()
    public String examSchedule()
    {
        return prefix + "/examSchedule";
    }

    /**
     * 查询考场安排列表
     */
    @RequiresPermissions("school:examSchedule:list")
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(ExamRoomSchedule examRoomSchedule)
    {
        startPage();
        examRoomSchedule.setSchoolId(SchoolUtil.getSchoolId());
        List<ExamRoomSchedule> list = examRoomScheduleService.selectExamRoomScheduleList(examRoomSchedule);
        return getDataTable(list);
    }

    /**
     * 导出考场安排列表
     */
    @RequiresPermissions("school:examSchedule:export")
    @Log(title = "考场安排", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    @ResponseBody
    public AjaxResult export(ExamRoomSchedule examRoomSchedule)
    {
        examRoomSchedule.setSchoolId(SchoolUtil.getSchoolId());
        List<ExamRoomSchedule> list = examRoomScheduleService.selectExamRoomScheduleList(examRoomSchedule);
        ExcelUtil<ExamRoomSchedule> util = new ExcelUtil<ExamRoomSchedule>(ExamRoomSchedule.class);
        return util.exportExcel(list, "examSchedule");
    }

    /**
     * 新增考场安排
     */
    @GetMapping("/add")
    public String add(ModelMap mmap)
    {
        getGradeList(mmap);
        return prefix + "/add";
    }

    private void getGradeList(ModelMap mmap) {
        Grade grade = new Grade();
        grade.setShcoolId(SchoolUtil.getSchoolId());
        List<Grade> glist = gradeService.selectGradeList(grade);
        mmap.put("grades",glist);
    }

    /**
     * 新增保存考场安排
     */
    @RequiresPermissions("school:examSchedule:add")
    @Log(title = "考场安排", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @ResponseBody
    public AjaxResult addSave(ExamRoomSchedule examRoomSchedule)
    {
        SysUser currUser = ShiroUtils.getSysUser();
        examRoomSchedule.setCreateBy(currUser.getUserName());
        examRoomSchedule.setSchoolId(SchoolUtil.getSchoolId());
        examRoomSchedule.setCreateTime(DateUtils.getNowDate());
        return toAjax(examRoomScheduleService.insertExamRoomSchedule(examRoomSchedule));
    }

    /**
     * 修改考场安排
     */
    @GetMapping("/edit/{id}")
    public String edit(@PathVariable("id") Long id, ModelMap mmap)
    {
        ExamRoomSchedule examRoomSchedule = examRoomScheduleService.selectExamRoomScheduleById(id);
        mmap.put("examRoomSchedule", examRoomSchedule);
        getGradeList(mmap);
        return prefix + "/edit";
    }

    /**
     * 打印考场安排
     */
    @GetMapping("/print/{id}")
    public String print(@PathVariable("id") Long id, HttpServletRequest request, HttpServletResponse response)
    {
        ExamRoomSchedule examRoomSchedule = examRoomScheduleService.selectExamRoomScheduleById(id);

        ExamRoomClasses classes = new ExamRoomClasses();
        classes.setScheduleId(id);
        List<ExamRoomClasses> roomList = examRoomClassesService.selectExamRoomClassesList(classes);
        if(CollectionUtils.isNotEmpty(roomList)){//教室是否为空
            for(ExamRoomClasses room:roomList){
                ExamRoomStudents students = new ExamRoomStudents();
                students.setClazzId(room.getId());
                List<ExamRoomStudents> studentsList = examRoomStudentsService.selectExamRoomStudentsList(students);
                room.setStudentsList(studentsList);
            }
            examRoomSchedule.setList(roomList);
            response.setDateHeader("Expires", 0);
            response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");
            response.addHeader("Cache-Control", "post-check=0, pre-check=0");
            response.setHeader("Pragma", "no-cache");
            response.setContentType("image/png");
            OutputStream out = null;
            try {
                String temp = Global.getDownloadPath()+"temp/";
                File file = new File(temp);
                if(!file.exists()){
                    file.mkdirs();
                }
                String fullName = PdfUtil.createExamSitesPdf(examRoomSchedule,temp);
                logger.info(fullName);
                File f0 = new File(fullName);
                if(f0.exists()){
                    out = response.getOutputStream();
                    String headerKey = "Content-Disposition";
                    String headerValue = String.format("attachment; filename=\"%s\"",
                            f0.getName());
                    response.setHeader(headerKey, headerValue);
                    InputStream myStream = new FileInputStream(fullName);
                    IOUtils.copy(myStream, out);
                }
                response.flushBuffer();
            } catch (IOException e) {
                e.printStackTrace();
            }finally {
                try {
                    if(out!=null)
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return null;
    }

    /**
     * 打印考场安排
     */
    @GetMapping("/print2/{id}")
    public String print2(@PathVariable("id") Long id, ModelMap mmap)
    {
        ExamRoomSchedule examRoomSchedule = examRoomScheduleService.selectExamRoomScheduleById(id);
        ExamRoomClasses classes = new ExamRoomClasses();
        classes.setScheduleId(id);
        mmap.put("schedule",examRoomSchedule);
        List<JSONObject> array = new ArrayList<>();
        List<ExamRoomClasses> roomList = examRoomClassesService.selectExamRoomClassesList(classes);
        if(CollectionUtils.isNotEmpty(roomList)){//教室是否为空
            for(ExamRoomClasses room:roomList){
                JSONObject j0 = new JSONObject();
                j0.put("examName",examRoomSchedule.getName());
                j0.put("clazzId",room.getRoomId());
                j0.put("location",room.getLocation());
                ExamRoomStudents students = new ExamRoomStudents();
                students.setClazzId(room.getId());
                List<ExamRoomStudents> studentsList = examRoomStudentsService.selectExamRoomStudentsList(students);
                List<JSONObject> listStu = new ArrayList<>();
                if(studentsList!=null&&studentsList.size()>0){
                    int total = studentsList.size();
                    int k0 = total/2;
                    int yk = total%2;
                    if(yk>0)
                        k0+=1;
                    for(int i = 0;i<k0;i++){
                        ExamRoomStudents s0 = studentsList.get(i);
                        JSONObject stJson = new JSONObject();
                        stJson.put("site0",s0.getSiteNo());
                        stJson.put("studentNo0",s0.getStudentNo());
                        stJson.put("studentName0",s0.getStudentName());
                        int k = i+k0;
                        if(total>k){
                            ExamRoomStudents s1 = room.getStudentsList().get(k);
                            stJson.put("site1",s1.getSiteNo());
                            stJson.put("studentNo1",s1.getStudentNo());
                            stJson.put("studentName1",s1.getStudentName());
                        }else{
                            stJson.put("site1","");
                            stJson.put("studentNo1","");
                            stJson.put("studentName1","");
                        }
                        listStu.add(stJson);
                    }
                }
                j0.put("list",listStu);
                array.add(j0);
            }
        }
        mmap.put("list",array);
        return prefix+"/print";
    }

    /**
     * 修改保存考场安排
     */
    @RequiresPermissions("school:examSchedule:edit")
    @Log(title = "考场安排", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(ExamRoomSchedule examRoomSchedule)
    {
        SysUser currUser = ShiroUtils.getSysUser();
        examRoomSchedule.setUpdateBy(currUser.getUserName());
        examRoomSchedule.setUpdateTime(DateUtils.getNowDate());
        return toAjax(examRoomScheduleService.updateExamRoomSchedule(examRoomSchedule));
    }



    /**
     * 删除考场安排
     */
    @RequiresPermissions("school:examSchedule:remove")
    @Log(title = "考场安排", businessType = BusinessType.DELETE)
    @PostMapping( "/remove")
    @ResponseBody
    public AjaxResult remove(String ids)
    {
        return toAjax(examRoomScheduleService.deleteExamRoomScheduleByIds(ids));
    }


    /**
     * 获取考试计划
     */
    @PostMapping("/getScheduleList")
    @ResponseBody
    public List<ExamRoomSchedule> getScheduleList() {
        ExamRoomSchedule schedule = new ExamRoomSchedule();
        schedule.setSchoolId(SchoolUtil.getSchoolId());
        List<ExamRoomSchedule> list = examRoomScheduleService.selectExamRoomScheduleList(schedule);
        return list;
    }

    @PostMapping("/getScheduleList2")
    @ResponseBody
    public List<ExamRoomSchedule> getScheduleList2(ExamRoomSchedule schedule) {
        schedule.setSchoolId(SchoolUtil.getSchoolId());
        List<ExamRoomSchedule> list = examRoomScheduleService.selectExamRoomScheduleList(schedule);
        return list;
    }
}
